package com.weipai.springboot.module.controller;

import com.weipai.springboot.enums.Payment;
import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.Order;
import com.weipai.springboot.model.OrderSublist;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.module.mapper.OrderMapper;
import com.weipai.springboot.module.mapper.OrderSublistMapper;
import com.weipai.springboot.module.service.OrderService;
import com.weipai.springboot.module.service.PayService;
import com.weipai.springboot.module.service.impl.PayServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author songmengqiang
 * @create 2018-08-28 14:06
 * <p>
 * 支付管理模块
 **/
@RestController
public class PayController {
    private static final Logger log = LoggerFactory.getLogger(PayController.class);


    @Autowired
    private PayService payService;
    @Autowired
    private OrderService orderService;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    private OrderSublistMapper orderSublistMapper;

    /**
     * 返回支付方式列表
     *
     * @return
     */
    @GetMapping("/pay/payment")
    public Response getPayModeList() {
        return payService.getPayModeList();
    }

    /**
     * 微信pc支付监听此订单是否支付成功
     *
     * @param orderNumber
     * @return
     */
    @GetMapping("/pay/timerWxEwmPay")
    public Response timerWxEwmPay(String orderNumber) {
        return payService.timerWxEwmPay(orderNumber);
    }

    /*
         支付宝提现
     */
    @ResponseBody
    @RequestMapping("/pay/getWithdrawals")
    public Response getWithdrawals(Integer money) {
        return payService.getWithdrawals(money);
    }


    /**
     * 微信JSAPI接口
     * * @param orderNumber：订单号
     *
     * @param source：订单来源1是商品结算，2是需求订单结算
     * @return
     */
    @RequestMapping(value = "/pay/wxOrder")
    public Response wxOrder(String customerId, String orderNumber, Integer payment, String spbillCreateIp, String source, HttpServletRequest request, HttpServletResponse httpRespon) {
        log.info("=====进入微信JSAPI接口程序========");
        Response response = new Response();
        Order order = orderMapper.getOrderInfoByOrderNumber22(orderNumber);
        if (order != null && order.getRealPay() == 0) {
            response.setCode(RetCode.VAR_PRICE);
            return response;
        }  else if (order != null && order.getOrderStatus() != 1) {
            response.setCode(RetCode.NONSUPPORT);
            return response;
        } else {
            List<Map<String, Object>> sublistByOrderNumber = orderSublistMapper.getSublistByOrderNumber(order.getOrderNumber());
            Integer money = 0;
            boolean flags = false;
            for (Map<String, Object> stringObjectMap : sublistByOrderNumber) {
                Integer goodsPrice = (Integer) stringObjectMap.get("goodsPrice");
                Integer goodsNumber = (Integer) stringObjectMap.get("goodsNumber");
                money += goodsPrice * goodsNumber;
                if (goodsPrice == 0) {
                    flags = true;
                }
            }
            Integer freightMoney = order.getFreightMoney() * 100;
            Integer realMoney = order.getRealPay() - freightMoney;
            if (flags && realMoney <= money) {
                response.setCode(RetCode.VAR_PRICE);
                return response;
            }
            return payService.wxPayJsapi(request, orderNumber, payment, spbillCreateIp, source, customerId);
        }
    }


    /**
     * 支付接口
     *
     * @param orderNumber：订单号
     * @param payment：支付方式：1.支付宝，2.微信，3.银联卡，4.到付，5.信誉值付款
     * @param spbillCreateIp
     * @param source：订单来源1是商品结算，2是需求订单结算
     * @param flag：不传为移动端支付，flag=true则表示为pc端支付
     * @return
     */
    @PostMapping("/pay/payOrder")
    public Response payOrder(String orderNumber, Integer payment, String spbillCreateIp, String source,
                             @RequestParam(value = "flag", required = false) String flag,
                             HttpServletRequest request, HttpServletResponse httpRespon) {
        Response response = new Response();

        Order order = orderMapper.getOrderInfoByOrderNumber22(orderNumber);
        if (order != null && order.getRealPay() == 0) {
            response.setCode(RetCode.VAR_PRICE);
            return response;
        } else if (order != null && order.getOrderStatus() != 1) {
            response.setCode(RetCode.NONSUPPORT);
            return response;
        } else {
            List<Map<String, Object>> sublistByOrderNumber = orderSublistMapper.getSublistByOrderNumber(order.getOrderNumber());
            Integer money=0;
            boolean flags=false;
            for (Map<String, Object> stringObjectMap : sublistByOrderNumber) {
                Integer goodsPrice = (Integer) stringObjectMap.get("goodsPrice");
                Integer goodsNumber = (Integer) stringObjectMap.get("goodsNumber");
                money+=goodsPrice*goodsNumber;
                if (goodsPrice==0){
                    flags=true;
                }
            }
            Integer freightMoney = order.getFreightMoney() * 100;
            Integer realMoney=order.getRealPay()-freightMoney;
            if (flags&&realMoney<=money){
                response.setCode(RetCode.VAR_PRICE);
                return response;
            }
            if (payment == Payment.ALI_PAY.getType() && flag == null) {
                return payService.aliPay(orderNumber, payment, source);
            } else if (payment == Payment.WX_PAY.getType() && flag == null) {
                return payService.wxPay(orderNumber, payment, spbillCreateIp, source);
            } else if (payment == Payment.COLLECT_PAY.getType()) {
                return payService.collectPay(orderNumber, payment, source);
            } else if (payment == Payment.REPUTATION_PAY.getType()) {
                return payService.reputationPay(orderNumber, payment, source);
            } else if (payment == Payment.WX_PAY.getType() && flag.equals("true")) {
                payService.wxEwmPay(orderNumber, payment, spbillCreateIp, source, httpRespon);
                return null;
            } else if (payment == Payment.ALI_PAY.getType() && flag.equals("true")) {
                payService.aliEwmPay(orderNumber, payment, source, httpRespon);
                return null;
            } else {
                response.setCode(RetCode.REQUEST_ERROR);
                return response;
            }
        }
    }

    /**
     * 支付接口
     *
     * @param orderNumber：订单号
     * @param payment：支付方式：1.支付宝，2.微信，3.银联卡，4.到付，5.信誉值付款
     * @param spbillCreateIp
     * @param source：订单来源1是商品结算，2是需求订单结算
     * @param flag：不传为移动端支付，flag=true则表示为pc端支付
     * @return
     */
    @GetMapping("/pay/wxEwmPay")
    public Response wxEwmPay(String orderNumber, Integer payment, String spbillCreateIp, String source,
                             @RequestParam(value = "flag", required = false) String flag,
                             HttpServletRequest request, HttpServletResponse httpRespon) {
        Response response = new Response();
        if (payment == Payment.WX_PAY.getType() && flag.equals("true")) {
            return payService.wxEwmPay(orderNumber, payment, spbillCreateIp, source, httpRespon);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
            return response;
        }
    }


    /*
         信誉值支付 密码验证
   */
    @ResponseBody
    @RequestMapping("/pay/verPasswords")
    public Response verPasswords(String customerId, String password) {
        return payService.verPasswords(customerId, password);
    }


    /**
     * 积分换购商品
     *
     * @param integralAmount
     * @param goodsId
     * @return
     */
    @GetMapping("/pay/integralRedemption/{integralAmount}/{goodsId}")
    public Response integralRedemption(@PathVariable("integralAmount") String
                                               integralAmount, @PathVariable("goodsId") String goodsId) {
        return payService.integralRedemption(integralAmount, goodsId);
    }

    /**
     * 微信回调接口
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/pay/wxPayNotify")
    public String wxPayNotify(HttpServletRequest request) {
        return payService.wxPayNotify(request);
    }

    /**
     * 微信pc扫码支付回调接口
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/pay/wxEwmPayNotify")
    public void wxEwmPayNotify(HttpServletRequest request, HttpServletResponse response) {
        payService.wxEwmPayNotify(request, response);
    }

    /**
     * 支付宝回调
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/pay/aliPayNotify")
    public String aliPayNotify(HttpServletRequest request, HttpServletResponse response) {
        return payService.aliPayNotify(request);
    }


    /**
     * 银联支付
     *
     * @param resp
     * @param orderId：订单号
     * @param txnAmt：交易金额，单位为分
     * @param txnTime：订单发送时间，格式：YYYYMMDDhhmmss
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/pay/unionPay")
    public void unionPay(HttpServletResponse resp, String orderId,
                         String txnAmt, String txnTime) throws IOException {
        payService.unionPay(resp, orderId, txnAmt, txnTime);
    }

    /**
     * 银联支付回调
     *
     * @param req
     * @param resp
     */
    @RequestMapping("/pay/unionPayNotify")
    public void unionPayNotify(HttpServletRequest req, HttpServletResponse resp) {
        payService.unionPayNotify(req, resp);
    }


    /**
     * 银联支付 *前台请求地址
     *
     * @param req
     * @param resp
     */
    @RequestMapping("/pay/goFrontUrl")
    public void goFrontUrl(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        payService.goFrontUrl(req, resp);
    }


}
